/*
 * @lc app=leetcode.cn id=113 lang=cpp
 *
 * [113] 路径总和 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    vector<vector<int>> ans;
    void dfs(vector<int> &res, TreeNode *root, int curr_sum, const int targetSum)
    {
        // if (curr_sum > targetSum)
        // {
        //     return;
        // }

        res.push_back(root->val);

        if (curr_sum + root->val == targetSum && (root->left == NULL && root->right == NULL))
        {
            //左右子树都是null才能保证当前节点是叶子节点
            ans.push_back(res);
        }

        if (root->left)
            dfs(res, root->left, curr_sum + root->val, targetSum);
        if (root->right)
            dfs(res, root->right, curr_sum + root->val, targetSum);

        res.erase(res.end() - 1);
    }
    vector<vector<int>> pathSum(TreeNode *root, int targetSum)
    {
        if (!root)
            return {};
        vector<int> res;
        dfs(res, root, 0, targetSum);
        return ans;
    }
};
// @lc code=end
